<?php
/*
*后台权限和用户角色管理
*/
/** * * ━━━━━━神兽出没━━━━━━
*       ┌─┐      ┌─┐
*     ┌─┘─┴──────┘─┴─┐
*     │              │
*     │      ─       │
*     │  ┬─┘   └─┬   │
*     │              │
*     │      ┴       │
*     │              │
*     └───┐      ┌───┘
*         │      │Code is far away from bug with the animal protecting ！
*         │      │神兽保佑,代码无bug！ 
*         │      └──────┐
*         │             ├┐
*         │             ┌┘
*         └┐ ┐ ┌───┬─┐ ┌┘
*          │ ┤ ┤   │ ┤ ┤
*          └─┴─┘   └─┴─┘
* ━━━━━━感觉萌萌哒━━━━━━
*/ 
namespace app\admin\controller;
use think\Controller;
use think\Request;
use \think\Db;
class Systems extends Base{




    /*
    * 角色列表
     */
    public function role_list(){
    	$list = Db::name(self::$tb['sys_role'])->select();
    	foreach ($list as $key => $value) {
    		$list[$key]['user_num'] = Db::name(self::$tb['sys_user'])->where("sys_role_id",$value['id'])->count();
    	}
    	$this->assign("list",$list);
    	return $this->fetch();
    }


    /*
    * 角色详情
    */
    public function role_detail(){
       $data = $this->data;
       $where = []; 
       if(isset($data['id'])){ $where['id'] = $data['id']; 
         $detail = Db::name(self::$tb['sys_role'])->where($where)->find();
         $this->assign("detail",$detail);
       }
       return $this->fetch();
    }

     /*
    * 编辑角色
     */
    public function edit_role(){
    	$data = $this->data;
    	if(isset($data['id']) && !empty($data['id'])){
    	  $update['name'] = $data['name'];
    	  $res = Db::name(self::$tb['sys_role'])->where("id",$data['id'])->update($update);	
    	}else{
    		$insert = [
    		  "name"=>$data['name'],
    		  "addtime"=>time()
    		];
    		$res = Db::name(self::$tb['sys_role'])->insert($insert);
    	}
    	if($res){
          $this->success("保存成功","Systems/role_list");
        }else{
          $this->error("保存失败");
        }
    }



   /*
   *删除角色
   */
    public function delete_role(){
      $data =$this->data;
       if(!isset($data['id'])){
          $this->error("缺少id");
      }
      //查看是否有用户
      $user = Db::name(self::$tb['sys_user'])->where("sys_role_id",$data['id'])->value("id");
      if($user){
        $this->error("该角色下面还有用户,不能删除"); 
      }
      $where=['id'=>$data['id']];
      Db::startTrans();
       try{
          Db::name(self::$tb['sys_role'])->where($where)->delete();
          //删除角色关联表
          Db::name(self::$tb['sys_role_permission'])->where("sys_role_id",$data['id'])->delete();
          Db::commit();
           $this->success("操作成功");
        } catch (\Exception $e) {
          Db::rollback(); 
           throw($e);
            $this->error("操作失败");
        } 
    }



    /*
    * 后台的权限列表
    */
/*    public function permission_list(){
      $data = $this->data;
      $where = []; 
      $list = Db::name(self::$tb['sys_permission'])->where($where)->select();
      $data =[];
      foreach ($list as $key => $value) {
        $data[$value['category']][] = $value;
      }
      $this->assign("list",$data);
      return $this->fetch();
    }*/


    /*
    * 角色对应的权限列表
    */
    public function role_permission(){
      $data = $this->data;
      if(!isset($data['role_id'])){
          $this->error("缺少角色id");
      }
      //所有的权限列表 
      $list = Db::name(self::$tb['sys_permission'])->order("category,id")->field("id,category,name")->select();
      //分类
      $category = Db::name(self::$tb['sys_permission'])->distinct(true)->field('category')->select(); 
      //当前的角色
      $where=['rs.sys_role_id'=>$data['role_id']];
      $field = "p.id,p.category,p.name";
      $list = Db::name(self::$tb['sys_permission'])->order("category,id")->field("id,category,name")->select();
      $role_list = Db::name(self::$tb['sys_role_permission'])->alias("rs")->join("jun_sys_permission p","p.id=rs.sys_permission_id","left")->where($where)->field($field)->select(); 
      foreach ($list as $key => $value) { 
        $list[$key]['ins'] = in_array($value,$role_list)?1:0;  
      }  
      
      foreach ($category as $key => $value) {
        $category[$key]['child'] = [];
        foreach ($list as $k => $v) {
          if($v['category']  == $value['category']){
             $category[$key]['child'][] = $v;
          }
        }
      } 
      $this->assign("role_id",$data['role_id']); 
      $this->assign("lists",$category); 
      return $this->fetch();
    }

    /*
    * 角色编辑权限
     */
    public function edit_role_permission(){
       $data = $this->data;  
       if(!isset($data['sys_role_id'])){
          $this->error("缺少角色id");
       }
       if(!isset($data['permision_list'])){
          $this->error("缺少权限列表");
       }
       $exist = Db::name(self::$tb['sys_role'])->where("id",$data['sys_role_id'])->value("id");
       if(!$exist){
          $this->error("该角色不存在");
       }
       $result = false;
       Db::startTrans();
       try{
         $where=  ['sys_role_id'=>$data['sys_role_id']];
         $delete =  Db::name(self::$tb['sys_role_permission'])->where($where)->delete();
         foreach ($data['permision_list'] as $key => $value) {
           $insert[] = [
             'sys_role_id'=>$data['sys_role_id'],
             'sys_permission_id'=>$value,
             'addtime'=>time()
           ];
         }
         $res = Db::name(self::$tb['sys_role_permission'])->insertAll($insert); 
         if($res){
             Db::commit();
            $result = true;
         } 
      } catch (\Exception $e) {
          Db::rollback(); 
           throw($e);
           $result = false;
      } 

      if($result){
        $this->success("保存成功","Systems/role_list");
      }else{
        $this->error("保存失败");
      }

    }



       /*
    * 获取用户列表
     */
    public function user_list(){
    $data = $this->data;
    $where = [];
    if(isset($data['role_id']) && !empty($data['role_id'])){
      $where['sys_role_id'] = $data['role_id'];
    }
    $field = "u.id,u.name,u.username,u.phone,u.addtime,r.name as role_name";
    $list = Db::name(self::$tb['sys_user'])->alias('u')->join("jun_sys_role r","r.id = u.sys_role_id")->where($where)->field($field)->paginate(10);
    //$datas = $list->all();  
    $page = $list->render();
    $this->assign("list",$list);
    $this->assign("page",$page); 
    return $this->fetch();
    }

  /*
  * 获取用户详情
   */
    public function user_detail(){
      $data = $this->data;
      if(isset($data['id'])){
        $where = ["id"=>$data['id']];
        $detail = Db::name(self::$tb['sys_user'])->where($where)->field("id,name,phone,sys_role_id,username")->find();
        $this->assign("detail",$detail); 
      }
      $role_list = Db::name(self::$tb['sys_role'])->select();
      $this->assign("role_list",$role_list);
      return $this->fetch();
    }


  /*
  * 编辑用户
   */
    public function user_edit(){
      $data = $this->data;
      if(isset($data['id']) && !empty($data['id'])){
        $update['name'] = $data['name'];
        $update['phone'] = $data['phone'];
        $update['sys_role_id'] = $data['sys_role_id'];
        $res = Db::name(self::$tb['sys_user'])->where("id",$data['id'])->update($update); 
      }else{

        if(preg_match('/[\x{4e00}-\x{9fa5}]/u', $data['username'])>0) {
           $this->error("账号不能有中文");
        } 
        $insert = [
          "name"=>$data['name'],
          "phone"=>$data['phone'],
          "username"=>$data['username'],
          "password"=>MD5("123456"),
          "sys_role_id"=>$data['sys_role_id'],
          "addtime"=>time()
        ];
        $res = Db::name(self::$tb['sys_user'])->insert($insert);
      }
      if($res){
          $this->success("保存成功","Systems/role_list");
        }else{
          $this->error("保存失败");
        }
    }

    /*
    * 删除用户
    */
    public function delete_user(){
      $data = $this->data;
      if(!isset($data['id'])){
       $this->error("缺少用户id");
      }
      $where = ['id'=>$data['id']];
      $res = Db::name(self::$tb['sys_user'])->where($where)->delete();
      if($res){
          $this->success("操作成功","Systems/role_list");
      }else{
          $this->error("操作失败");
      }
    }


    /*修改密码页面*/
    public function password_edit(){
       $data = $this->data;
       if(isset($data["id"]) && !empty($data['id'])){
         $user_id = $data['id'];
       }else{
         $user = session("user_id");
         $user_id = $user['id']??'';  
       } 
       $this->assign("id",$user_id);
        return $this->fetch();
    }

    /*
    * 修改密码
    */
    public function edit_password(){
      $data = $this->data;
      $check = $this->validate($data,'Systems.password');
      if($check !==true){
        $this->error("参数缺失");
      }

      $check = Db::name(self::$tb['sys_user'])->where(["id"=>$data['id'],"password"=>md5($data['oldpassword'])])->value("id");
      if(!$check){
        $this->error("旧密码不对");
      } 
      if($data['newpassword'] !== $data['confirmpassword']){
         $this->error("两个密码不一致"); 
      }
      $update['password'] = MD5($data['newpassword']);
      $result = Db::name(self::$tb['sys_user'])->where("id",$check)->update($update);
      if($result){
          $this->success("操作成功,请重新登录","Login/index");
      }else{
          $this->error("操作失败");
      }
    }


    /*
    * 后台的权限列表
    */
    public function permission_list(){
      $data = $this->data;
      $where = [];
      $field = "id,name,category,val,addtime";
      $list = Db::name(self::$tb['sys_permission'])->where($where)->field($field)->order("category")->paginate(10);  
      $page = $list->render();
      $this->assign("list",$list);
      $this->assign("page",$page); 
      return $this->fetch();
    }


   /*
    * 后台的权限详情
    */
    public function permission_detail(){
      $data = $this->data;
       if(isset($data['id']) && !empty($data['id'])){
        $detail= db::name(self::$tb['sys_permission'])->where('id',$data['id'])->find();
        $this->assign("detail",$detail); 
       }
       return $this->fetch();
    }

   /*
    * 后台的权限编辑
    */
    public function permission_edit(){
      $data = $this->data;
      $insert = [
        'name'=>$data['name'],
        'category'=>$data['category'],
        'val'=>$data['val']
      ];
      if(isset($data['id']) && !empty($data['id'])){
        $res = Db::name(self::$tb['sys_permission'])->where("id",$data['id'])->update($insert); 
      }else{
        $insert['addtime'] = time();
        $res = Db::name(self::$tb['sys_permission'])->insert($insert); 
      }
      if($res){
          $this->success("操作成功","Systems/permission_list");
      }else{
          $this->error("操作失败");
      }
    }

   /*
    * 后台的权限编辑
    */
    public function delete_permission(){
      $data = $this->data;
      $res = Db::name(self::$tb['sys_permission'])->where("id",$data['id'])->delete();
      if($res){
          $this->success("操作成功","Systems/permission_list");
      }else{
          $this->error("操作失败");
      }

    }
    
 
}
